import pandas as pd
import warnings


def drop_same(filtered_data, column):
    filtered_data[column] = filtered_data[column].str.lower().str.strip()
    filtered_data.drop_duplicates(subset=column, keep='first', inplace=True)
    new_df = pd.DataFrame({'name': filtered_data['成员英文名']})
    return new_df


class Separate:
    def __init__(self):
        warnings.filterwarnings('ignore')
        self.base_path = 'D:/Code/程序/python/twitter/myTwitter'
        self.username = 'RAND Corporation'
        """读取CSV文件为DataFrame"""
        self.data_df = pd.read_excel(rf'{self.base_path}/data/excel/1 RAND Corporation.xlsx',
                                     header=1)
        """种子保存地址"""
        self.seed_dir = rf'{self.base_path}/data/seed/{self.username}_seed.xlsx'
        """有照片保存地址"""
        self.image_dir = rf'{self.base_path}/data/image/{self.username}_image.xlsx'
        """无照片保存地址"""
        self.notimage_dir = rf'{self.base_path}/data/noimage/{self.username}_notImage.xlsx'
        """字段"""
        self.column_to_check = '成员英文名'
        self.column_to_twitter = '成员twitter帐号'
        self.column_to_image = '成员照片'

        self.data_df[self.column_to_check] = self.data_df[self.column_to_check].str.lower().str.strip()
        self.grouped = self.data_df.groupby(self.column_to_check)

    """定义一个函数，根据条件选择保留的行,分组"""

    def filter_group(self, group):
        if len(group) == 1:
            return group
        else:
            has_both_b_and_c = group[self.column_to_twitter].notnull() & group[self.column_to_image].notnull()
            if has_both_b_and_c.any():
                return group[has_both_b_and_c]
            elif group[self.column_to_twitter].notnull().any():
                return group.dropna(subset=[self.column_to_twitter])
            elif group[self.column_to_image].notnull().any():
                return group.dropna(subset=[self.column_to_image])
            else:
                return group.head(1)

    def run(self):
        """使用apply函数在每个分组中根据条件筛选行"""
        df = self.grouped.apply(self.filter_group)

        """种子"""
        data = df[df[self.column_to_twitter].notnull()]
        new_df = pd.DataFrame(
            {
                'name': data[self.column_to_check],
                'twitter_username': data[self.column_to_twitter].astype(str).str.split('.com/').str[1]
            }
        )
        new_df.to_excel(self.seed_dir, index=False)
        print('存入种子的数据完成')
        pending_data = df[~df[self.column_to_twitter].notnull()]

        """有照片的数据"""
        have_image = pending_data[pending_data[self.column_to_image].notnull()][self.column_to_check]
        """have_image=drop_same(have_image,'成员英文名')"""
        have_image.to_excel(self.image_dir, index=False)
        print('存入有照片的数据完成')

        no_image = pending_data[pending_data[self.column_to_image].isnull()][self.column_to_check]  # 没有照片
        """no_image=drop_same(no_image,'成员英文名')"""
        no_image.to_excel(self.notimage_dir, index=False)
        print('存入无照片的数据完成')
